package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.AESUtil;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class FindWordActivity extends BaseActivity implements View.OnClickListener{
    private String url = "http://192.168.3.77:8088/YiViOnlineServer";// 接口
    private ImageView findback;
    private EditText findnumber;
    private EditText findword;
    private EditText findincode;
    private Button findcode;
    private TextView findtoup;
    private TextView findwordbt;
    private Button findup;

    private String number;
    private String code;
    private String word;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private String data;
    private String messageId;
    private SharedPreferences.Editor edit;
    private String messageId1;
    private String AWord;
    private ImageView backmain;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_word);
        initFindView();
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("uesrId", "1");
        token = sharedPreferences.getString("token", "2");
        messageId1 = sharedPreferences.getString("messageId1", "3");

    }

    private void initFindView() {
        backmain = (ImageView) findViewById(R.id.findword_backmain);
        findback = (ImageView) findViewById(R.id.find_back);
        findnumber = (EditText) findViewById(R.id.find_inputphonenumber);
        findword = (EditText) findViewById(R.id.find_inputword);
        findincode = (EditText) findViewById(R.id.find_incode);
        findcode = (Button) findViewById(R.id.find_code);
        findtoup = (TextView) findViewById(R.id.find_toup);
        findwordbt = (TextView) findViewById(R.id.find_wordbt);
        findup = (Button) findViewById(R.id.find_up);
        findtoup.setOnClickListener(this);
        findwordbt.setOnClickListener(this);
        findcode.setOnClickListener(this);
        findup.setOnClickListener(this);
        backmain.setOnClickListener(this);

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.findword_backmain:

                startActivity(new Intent(FindWordActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.find_back:// 离开页面
                finish();
                break;
            case R.id.find_code:// 获取验证码
                String number = String.valueOf(findnumber.getText());
                if (number.equals("")){
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }else {

                    MyTimer timer = new MyTimer(120000,1000);
                    timer.start();
                    getCode();

                }
                break;
            case R.id.find_up:// 提交修改密码
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        findtoword();
                    }
                }).start();

                break;
            case R.id.find_toup://去登陆
                startActivity(new Intent(this,UserRegistActivity.class));
                finish();
                break;
            case R.id.find_wordbt:
                startActivity(new Intent(this,UserRegistActivity.class));
                finish();
                break;
        }

    }

    // 获取输入手机号和验证码
    private  void getInText(){
        number = String.valueOf(findnumber.getText());
        code = String.valueOf(findincode.getText());
        word = String.valueOf(findword.getText());
        try {
            AWord = AESUtil.encryptAES(word);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        // 忘记密码 重新设置
    private void findtoword() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/user/forgetPassword");
        params.addHeader("Content-Type","application/json");
        getInText();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("password",AWord);
        jsonObject.put("mobile",number);
        jsonObject.put("messageId",messageId1);
        jsonObject.put("code",code);
        params.setBodyContent(jsonObject.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    Toast.makeText(FindWordActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                }else if (status.equals("1005")){
                    Toast.makeText(FindWordActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                }else if (status.equals("1009")){
                    Toast.makeText(FindWordActivity.this, "手机号未注册", Toast.LENGTH_SHORT).show();
                }else if (status.equals("1003")){
                    Toast.makeText(FindWordActivity.this, "账号被禁用", Toast.LENGTH_SHORT).show();
                }else {}
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(FindWordActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });



    }

        // 获取验证码
    public void getCode() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/verify/sendCodeNotLogin");
        params.addHeader("Content-Type","application/json");
        getInText();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","4");
        jsonObject.put("mobile",number);
        params.addParameter("params",jsonObject.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                // 获取messageid
                data = obj.getString("data");
                com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                messageId1 = obj1.getString("messageId");

                sharedPreferences = getSharedPreferences("messageId", Context.MODE_PRIVATE);
                edit = sharedPreferences.edit();
                edit.putString("messageId1", messageId1);
                edit.commit();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(FindWordActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    class MyTimer extends CountDownTimer {
        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                  倒计时数        to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *           倒计时间隔               {@link #onTick(long)} callbacks.
         */
        public MyTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            findcode.setClickable(false);
            findcode.setText(millisUntilFinished/1000+" s 后发送");
        }

        @Override
        public void onFinish() {
            findcode.setClickable(true);
            findcode.setText("验证码");
        }
    }
}
